const conf = require("../conf")
const mdb = require("../helper/mongo")
const rdb = require("../helper/redis")
const Koa = require("koa")
const controller = require("../controller")
const app = new Koa()
const server = require('http').createServer(app.callback())
const koaBody = require("koa-body")
const koaStatic = require("koa-static")
const path = require("path")
const io = require("socket.io")(server)
const logger = require("../middleware/logger")
const origin = require("../middleware/origin")
const catchError = require("../middleware/catcherror")
const p404 = require("../middleware/404")
const {logger:log} = require("../utils")
app.use(origin)
app.use(logger)
app.use(koaStatic(path.join(path.dirname(__dirname), "static")))
app.use(koaBody(conf.web.uploadOptions))


module.exports = {
  start: () => {
    app.use(async (ctx, next) => {
      if (!process.mdb) {
        process.mdb = await mdb.connect()
      }
      if (!process.rdb) {
        process.rdb = await rdb()
      }
      await next()
    })
    app.use(controller.routes())
    app.use(catchError)
    app.use(p404)
    server.on("checkContinue",(req,res)=>{
        res.writeContinue()
    })
    server.listen(conf.web.port, () => {
      console.log(`web server listen at ${conf.web.host}:${conf.web.port}`)
    })
    io.on("connection", socket => {
      socket.emit("msg", {pong: Date.now()})
      socket.on("msg", data => {
        socket.emit("msg",{pong: Date.now()})
      })
    })
  }
}
